<template>
  <q-page class="flex justify-center items-start bg-gradient">
    <!-- 主体卡片 -->
    <div class="card q-pa-xl q-mt-xl">
      <!-- 头部区域 -->
      <div class="row items-center q-mb-lg">
        <div class="q-ml-md">
          <HeaderCom
            :isLoading="isLoading"
            :LoginMessage="LoginMessage"
            :userInfo="userInfo"
            :handleLoginClick="handleLoginClick"
          />
        </div>
      </div>

      <!-- 主体内容区 -->
      <div class="row q-col-gutter-xl">
        <!-- 左侧信息栏 -->
        <div class="col-12 col-md-5" v-if="!isMobile">
          <div class="info-section q-mb-lg">
            <InfoBody />
          </div>

          <!-- 标签云 -->
          <div class="tags q-mb-lg" v-if="!isMobile">
            <TagsCom />
          </div>

          <!-- 外部链接 -->
          <div class="external-links"></div>
        </div>

        <!-- 右侧公告板块 -->
        <div class="col-12 col-md-7" v-if="!announcementsLoading">
          <div
            v-for="(group, index) in announcements"
            :key="index"
            class="q-mb-lg"
          >
            <q-card class="q-pa-md glassmorphism-effect">
              <!-- 修改这里 -->
              <q-card-section class="q-pb-none">
                <div class="row items-center">
                  <q-icon
                    :name="group.icon"
                    :color="group.color || 'primary'"
                    class="q-mr-sm"
                    size="24px"
                  />
                  <h4 class="text-h6">{{ group.title }}</h4>
                </div>
              </q-card-section>

              <q-item
                v-for="item in group.items"
                :key="item.title"
                class="q-my-sm"
                clickable
                @click="handleItemClick(item)"
              >
                <q-item-section avatar>
                  <q-img
                    v-if="item.image"
                    :src="item.image"
                    style="width: 60px; height: 60px"
                    class="rounded-borders"
                  />
                </q-item-section>
                <q-item-section>
                  <q-item-label class="text-weight-bold">{{
                    item.title
                  }}</q-item-label>
                  <q-item-label caption lines="2">{{
                    item.description
                  }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-card>
          </div>
        </div>
        <div class="col-12 col-md-7" v-else>
          <div v-for="i in 1" :key="i" class="q-mb-lg">
            <q-card class="q-pa-md glassmorphism-effect">
              <q-card-section class="q-pb-none">
                <q-skeleton type="rect" width="40%" height="30px" />
              </q-card-section>

              <q-item v-for="j in 1" :key="j" class="q-my-sm">
                <q-item-section avatar>
                  <q-skeleton type="circle" size="60px" />
                </q-item-section>
                <q-item-section>
                  <q-skeleton type="text" width="80%" />
                  <q-skeleton type="text" width="60%" />
                </q-item-section>
              </q-item>
            </q-card>
          </div>
        </div>
      </div>

      <!-- 音乐播放器 -->
      <MusicCom />

      <!-- 功能导航区 -->
      <div
        :class="'q-col-gutter-md q-mt-xl' + (isMobile ? '' : ' row')"
        v-if="!isMobile"
      >
        <div
          v-for="module in modules"
          :key="module.title"
          class="col-4 col-md-4"
        >
          <q-card class="module-card" @click="openModule(module)">
            <q-card-section class="q-pa-md">
              <div class="row items-center q-gutter-md">
                <!-- 图标区域 -->
                <div class="col-auto">
                  <q-icon
                    :name="module.icon"
                    size="30px"
                    class="text-primary"
                  />
                </div>

                <!-- 文字区域 -->
                <div class="col column">
                  <h3 class="text-h6 q-mb-xs">{{ module.title }}</h3>
                  <p class="text-grey-7 q-my-none" style="line-height: 1.4">
                    {{ module.description }}
                  </p>
                </div>

                <!-- 右侧提示 -->
                <div class="col-auto" v-if="module.isComingSoon">
                  <q-badge color="warning" class="q-ml-sm">敬请期待</q-badge>
                </div>
              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>

      <!-- 备案信息 -->
      <!-- <div class="footer text-center q-mt-xl">
        <p>ICP备案: 好像海外服务器不用备案也能访问，暂时不备案</p>
      </div> -->
    </div>
  </q-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { api } from "src/boot/axios";

import HeaderCom from "src/components/index/HeaderCom.vue";
import InfoBody from "src/components/index/InfoBody.vue";
import TagsCom from "src/components/index/TagsCom.vue";
import MusicCom from "src/components/index/MusicCom.vue";

const $q = useQuasar();

const announcements = ref([]);

const modules = reactive([
  {
    title: "博客",
    icon: "rss_feed",
    description: "分享日常，分享技术，分享生活",
    link: "https://blog.zhuchundashuaige.com",
    isComingSoon: false,
  },
  {
    title: "网盘",
    icon: "cloud_upload",
    description: "存储收集文件，图床，外链",
    link: "https://cloud.zhuchundashuaige.com",
    isComingSoon: false,
  },
  {
    title: "聚合搜索",
    icon: "search",
    description: "影视作品搜索、音乐搜索、小说搜索",
    link: "https://seach.zhuchundashuaige.com",
    isComingSoon: false,
  },
]);

// 社交媒体链接
const socialLinks = reactive([
  {
    name: "知乎",
    icon: "fa-brands fa-zhihu",
    url: "https://www.zhihu.com/people/@software-editor",
  },
]);

const handleItemClick = async (item) => {
  // 改为 async 函数
  if (!item?.link) return;

  if (item.link.startsWith("mailto:")) {
    // 动态加载邮件内容
    const mailBody = await getPublicResource(item.bodyPath);
    const encodedBody = encodeURIComponent(mailBody);
    window.location.href = `${item.link}${encodedBody}`;
  } else {
    window.open(item.link, "_blank");
  }
};

const getPublicResource = async (path) => {
  // 修正 public 资源路径（Vite 的 public 目录直接映射到根路径）
  return await fetch(path).then((res) => res.text());
};

// 打开功能模块
const openModule = (module) => {
  if (module.isComingSoon) {
    alert("功能开发中，敬请期待！");
  } else {
    window.open(module.link, "_blank");
  }
};

const handleLoginClick = () => {
  const encode = encodeURIComponent;
  window.location.href = `https://login.zhuchundashuaige.com/#/?RedirectUri=${encode(
    "http://" + window.location.host
  )}&Type=SPA`;
};

const windowWidth = ref(window.innerWidth);
const isMobile = computed(() => {
  return windowWidth.value < 650;
});
const email = ref("");
const token = ref("");
const isLoading = ref(false);
const LoginMessage = ref("");
const router = useRouter();
const userInfo = ref({
  display_name: "",
  email: "",
  given_name: "",
  surname: "",
  user_id: "",
  user_principal_name: "",
});

const handleLoginStatus = async () => {
  try {
    isLoading.value = true;
    const statusRes = await api.get("/api/v1/user_info", {
      headers: {
        ApiKey: btoa(
          `${localStorage.getItem("token") || ""}` +
            "$$" +
            `${localStorage.getItem("email") || ""}`
        ),
      },
    });
    userInfo.value = statusRes.data;
  } catch (e) {
    console.error(e);
    LoginMessage.value = e.response?.data?.error || "登录状态失效，请重试";
    localStorage.clear();
  } finally {
    isLoading.value = false;
  }
};

// 在script setup部分添加
const announcementsLoading = ref(false);

// 修改handleGetAnnouncements方法
const handleGetAnnouncements = async () => {
  try {
    announcementsLoading.value = true;
    const res = await api.get("/api/v1/announcements", {
      headers: {
        ApiKey: btoa(`${token.value}` + "$$" + `${email.value}`),
      },
    });
    announcements.value = res.data.items;
  } catch (e) {
    console.error(e);
  } finally {
    announcementsLoading.value = false;
  }
};

const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(async () => {
  // get LoginData from query
  const query = router.currentRoute.value.query;
  console.log(query);
  if (query?.LoginData) {
    const loginDataBase64 = JSON.parse(decodeURIComponent(query.LoginData));
    const LoginDataJSON = atob(loginDataBase64);
    const loginData = JSON.parse(LoginDataJSON);
    Object.entries(loginData).forEach(([key, value]) => {
      localStorage.setItem(key, value);
    });
    // remove LoginData from query
    await router.replace({
      path: router.currentRoute.value.path,
      query: {},
    });
    location.href =
      location.origin + "/#/" + (location.href.split("/#/")[1] || "");
    return;
  }
  if (location.search.includes("LoginData")) {
    // get params from query
    const params = new URLSearchParams(location.search);
    const LoginDataBase64 = params.get("LoginData");
    const LoginDataJSON = atob(LoginDataBase64);
    const loginData = JSON.parse(LoginDataJSON);
    Object.entries(loginData).forEach(([key, value]) => {
      localStorage.setItem(key, value);
    });
    // remove the url query
    location.search = "";
    location.href =
      location.origin + "/#/" + (location.href.split("/#/")[1] || "");
    return;
  }
  email.value = localStorage.getItem("email") || "";
  token.value = localStorage.getItem("token") || "";
  if (email.value && token.value) {
    await handleLoginStatus();
  }

  handleGetAnnouncements();

  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.text-h6 {
  color: #1a237e;
  margin: 8px 0;
}
.rounded-borders {
  border-radius: 8px;
}
.q-item__label--caption {
  color: #616161 !important;
}

.bg-gradient {
  background: url("/public/images/background.png") center/cover,
    linear-gradient(
      135deg,
      #1e88e5,
      #1976d2,
      #0d47a1,
      #082e6e,
      #0d47a1,
      #1976d2
    );
}

.card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  max-width: 1200px;
  width: 90%;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.name {
  color: #1565c0;
  font-weight: 700;
  margin-bottom: 0;
}

.info-section {
  padding: 15px;
  border-radius: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 1.1rem;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.module-card {
  transition: transform 0.3s;
  border-radius: 12px;
  cursor: pointer;
  height: 100%;
}

.module-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(30, 136, 229, 0.3);
}

.external-links {
  margin-top: 20px;
}

.avatar-decoration {
  position: absolute;
  right: -5px;
  top: -5px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #ff9800;
}

.footer {
  color: #757575;
  font-size: 0.9rem;
}

.glassmorphism-effect {
  background: rgba(255, 255, 255, 0.5) !important;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
}
</style>
